import 'dart:convert';
import 'dart:ui';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/models/oauth/linkRequest.dart';
import 'package:ichinesereader/utils/commonApi.dart';
import 'package:ichinesereader/utils/log.dart';

class OauthService extends GetConnect with CommonApi {
  final jsonEncoder = JsonEncoder();
  OauthService() {
    httpClient.addResponseModifier((request, response) {
      if (response.statusCode == 403) {
        Log.debug('${request.url} 403 error');
        if (!Get.isSnackbarOpen) {
          Get.snackbar(
            'Message'.tr,
            'You have been logged out due to inactivity or security reasons.'
                .tr,
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Color(0xff23c6c8),
            colorText: Color(0xffd8ffff),
          );
        }
        if (EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        if (Get.currentRoute != '/login') {
          return Get.offAllNamed('/login');
        }
      } else if (response.statusCode == 401) {
        Log.debug('${request.url} unauthorized access');
        if (!Get.isSnackbarOpen) {
          Get.snackbar('Message'.tr, 'Unauthorized access'.tr,
              backgroundColor: Color(0xff23c6c8),
              colorText: Color(0xffd8ffff),
              snackPosition: SnackPosition.BOTTOM);
        }
        if (EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        if (Get.currentRoute != '/login') {
          return Get.offAllNamed('/login');
        }
      } else {
        Log.debug(response.request?.url.toString());
        return response;
      }
    });
    httpClient.maxAuthRetries = 2;
    httpClient.timeout = Duration(seconds: 30);
  }

  Future<dynamic> callClasslink(String bearcode) async {
    final response = await get(
      '${Constants.BaseAPI}usermanager/classlink/$bearcode',
    );
    return response;
  }

  Future<dynamic> doLink(LinkRequest request) async {
    final response = await post(
        '${Constants.BaseAPI}usermanager/link', linkRequestToJson(request));
    return response;
  }
}
